package ua.ck.example.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ua.ck.example.domain.Order;

@Repository
public class OrderDAOImpl implements OrderDAO {
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public List<Order> listOrders() {
		return sessionFactory.getCurrentSession().createQuery("from Order")
				.list();
	}

	@Override
	public void addOrder(Order order) {
		sessionFactory.getCurrentSession().save(order);

	}

	@Override
	public void delOrder(Order order) {
		sessionFactory.getCurrentSession().delete(order);

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> getOrders(Order order) {
		StringBuffer sql = new StringBuffer("FROM Order as o");
		if (order.getCustomerId() == null && order.getEmployeeId() == null) {
			sql.append(" WHERE 1=1");
		}
		if (order.getCustomerId() != null) {
			sql.append(" join o.customer as c where o.customerId = c.customerId");
		}

		if (order.getEmployeeId() != null) {
			sql.append(" join o.employee as e where o.employeeId = e.employeeId");
		}

		if (order.getOrderId() != null) {
			sql.append(" and o.orderId=" + order.getOrderId());
		}

		return (List<Order>) sessionFactory.getCurrentSession()
				.createQuery(sql.toString()).list();
	}

	@Override
	public void updateOrder(Order order) {
		sessionFactory.getCurrentSession().update(order);

	}

	@Override
	public List<Order> getUnconfirmOrders() {
		StringBuffer sql = new StringBuffer(
				"FROM Order o WHERE employeeId is null");
		return (List<Order>) sessionFactory.getCurrentSession()
				.createQuery(sql.toString()).list();
	}

}
